package com.woniuxy.book.mq;

import com.woniuxy.book.util.RedisUtil;
import com.woniuxy.book.util.SMSUtil;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class SendRegisterMessageConsumer {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SMSUtil smsUtil;

    @RabbitListener(queuesToDeclare = {@Queue (name = "register.sendmessage")})
    @RabbitHandler
    public void comsumer(Map<String, Object> message) throws Exception {

        String userPhone = (String) message.get("userPhone");
        String codeKey = (String) message.get("codeKey");
        String codeMinuteKey = (String) message.get("codeMinuteKey");
        String sendNumbersKey = (String) message.get("sendNumbersKey");
        //调用短信平台api发送短信
        String code = smsUtil.send(userPhone);
        //将验证码保存到Redis中 设置过期时间5分钟
        redisUtil.set(codeKey, code, 5 * 60);
        //每发送一次短信保存一次key 过期时间为一分钟 当该key存在时 不允许再次发送
        redisUtil.set(codeMinuteKey, code, 60);
        //每发送一次短信使redis中的一个key的值自增1
        if (redisUtil.hasKey(sendNumbersKey)) {
            redisUtil.incr(sendNumbersKey);
        } else {
            redisUtil.set(sendNumbersKey, "1", 60 * 60);
        }
    }
}
